//
//  HomeViewController.m
//  微博2期
//
//  Created by J on 15/11/17.
//
//

#import "HomeViewController.h"
#import "TitleMenuViewController.h"
#import "DropDownMenu.h"
#import "AFNetworking.h"
#import "AccountTool.h"
#import "TitleButton.h"
#import "Status.h"
#import "User.h"
@interface HomeViewController ()<DropDownMenuDelegate>
@property(nonatomic,strong)NSMutableArray* statuses;//微博数组 。 一个字典代表一条微博

@end
@implementation HomeViewController


- (NSArray *)statuses{
    
    if (!_statuses) {
        
        self.statuses = [NSMutableArray array];
    }
    return _statuses;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置导航栏内容
    [self setupNav];
    
    //获取用户信息(昵称)
    
    [self setupUserInfo];
    
    //即成刷新控件
    [self setupRefresh];
    
    //获得未读数
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(setupUnreadCount) userInfo:nil repeats:YES];
    
    
}
//即成刷新控件
- (void)setupRefresh{
   //原生只有下拉刷新
    UIRefreshControl * control =[[UIRefreshControl alloc]init];
    [control addTarget:self  action:@selector(refreshStateChange:) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:control];
    [control beginRefreshing];//只是开启动画并不会调用刷新方法
    [self refreshStateChange:control];
}

- (void)refreshStateChange:(UIRefreshControl*)control{
    //刷新成功(清空图标数字)
    
    //1.请求管理者
    AFHTTPRequestOperationManager * manager= [AFHTTPRequestOperationManager manager];
    //2.拼接请求参数
    Account  * account = [AccountTool account];
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];

    Status * firtstStatus = [self.statuses firstObject];
    params[@"access_token"]=account.access_token;
    if (firtstStatus) {//如果第一条微博存在 取出
        //若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
        params[@"since_id"]=firtstStatus.idstr;
    }
   

    [manager GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary*  responseObject) {
        NSArray * newStatus = [Status objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
        //插入最新数据
        [self.statuses insertObjects:newStatus atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, newStatus.count)]];

        //刷新表格
        [self.tableView reloadData];
        
        //结束刷新
        [control endRefreshing];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
        //结束刷新
        [control endRefreshing];
        NSLog(@"%@",error);
        
    }];
    
    
}


//获取用户信息(昵称)

- (void)setupUserInfo{
    
//    https://api.weibo.com/2/users/show.json
//    access_token&uid
    
    
    //1.请求管理者
    AFHTTPRequestOperationManager * manager= [AFHTTPRequestOperationManager manager];
    //2.拼接请求参数
    Account  * account = [AccountTool account];
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"uid"]=account.uid;
    params[@"access_token"]=account.access_token;
       [manager GET:@"https://api.weibo.com/2/users/show.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary*  responseObject) {

        NSString * name =    responseObject[@"screen_name"];
           UIButton * titleButotn = (UIButton*)self.navigationItem.titleView;
           [titleButotn setTitle:name forState:UIControlStateNormal];//标题文字到按钮

           //存储昵称到沙盒
           account.name = name;
           [AccountTool saveAccount:account];
       } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);

    }];
    
    
    
}
//设置导航栏内容

- (void)setupNav{
    
    //设置导航栏内容
    //设置左边返回按钮
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(friendSearch) image:@"navigationbar_friendsearch" highImage:@"navigationbar_friendsearch_highlighted"];
    
    //设置右边更多按钮
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(pop) image:@"navigationbar_pop" highImage:@"navigationbar_pop_highlighted"];
    
    //中间标题按钮
    TitleButton * titleButton = [[TitleButton alloc]init];
 
    //按钮设置文字要用状态的方式
    NSString* name = [AccountTool account].name;
    
    [titleButton setTitle:name?name:@"首页" forState:UIControlStateNormal];
    //监听标题点击
    [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];

    self.navigationItem.titleView = titleButton;

}
- (void)titleClick:(UIButton*)button{
    //显示下拉菜单
    DropDownMenu* menu =  [DropDownMenu menu];
    menu.delegate = self;
    TitleMenuViewController * vc= [[TitleMenuViewController alloc]init];
    vc.view.height = 44*3;
    vc.view.width = 150;

    menu.contentViewcontroller = vc;
     // 显示
    [menu showFrom:button];

  }


#pragma mark --改变按钮的图片
- (void)dropdownMenuDidDismiss:(DropDownMenu *)menu{
    UIButton * button = (UIButton*)self.navigationItem.titleView;
    //让箭头向下
    button.selected = NO;
    
}


//下拉菜单显示了
-(void)dropdownMenuDidShow:(DropDownMenu *)menu{
    UIButton * button = (UIButton*)self.navigationItem.titleView;
    //    4.让箭头向上
    button.selected = YES;

}

- (void)friendSearch{
    //这里sel本身就是一个导航控制器 self.navigationController ==null
}

- (void)pop{
    [self.navigationController popToRootViewControllerAnimated:YES];//返回根控制器
    


}



#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    
    
    return self.statuses.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"ID"];
    }
    //取出row对应的微博字典
    Status * status =self.statuses[indexPath.row];
    
    //取出用户名
    cell.textLabel.text = status.user.name;
    //设置头像
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:status.user.profile_image_url]];
    //微博内容 
    cell.detailTextLabel.text =status.text;

    return cell;
    
    
    
}
@end
